package com.batchOperation.excel.support;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Map;

/**
 * @Package: com.batchOperation.excel.support
 * @ClassName: SpringHolder
 * @Author: wulongkai
 * @CreateTime: 2024/7/20 10:15
 * @Description:
 */
@Component
public class SpringHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 获取spring容器中的bean
     *
     * @param requiredType 需要获取的实例类型
     * @param <T>          需要获取的实例泛型
     * @return 对象实例
     */
    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    /**
     * 获取spring容器中某一类型的所有类实例
     *
     * @param requiredType 需要的类型
     * @return 类实例集合
     */
    public static <T> Collection<T> getBeansOfType(Class<T> requiredType) {
        Map<String, T> beansOfType = applicationContext.getBeansOfType(requiredType);
        if (CollectionUtils.isEmpty(beansOfType)) {
            return null;
        }
        return beansOfType.values();
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        SpringHolder.applicationContext = applicationContext;
    }
}

